package com.lam.framework.mybatis;


import javax.sql.DataSource;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.lam.common.utils.StringUtils;

/**
 * mybatis 配置数据源类
 * @author lam
 *
 */
@MapperScan("com.lam.**.mapper")
@Configuration
@EnableTransactionManagement
public class MybatisConfiguration {
	
    @Bean
    public DataSourceTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        dynamicTableNameInnerInterceptor.setTableNameHandler((sql, tableName) -> {
            // 获取表后缀
        	String tableSuffix = MybatisRequestHelper.getTableSuffix();
        	if(StringUtils.isBlank(tableSuffix)) {
        		return tableName;
        	}
            return String.format("%s_%s", tableName, tableSuffix);
        });
        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
        // dynamicTableNameInnerInterceptor.setTableNameHandlerMap(map);// 3.4.3.2 作废该方式
        return interceptor;
    }
}
